package com.dev.security.shiro;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * Shiro框架配置类
 *
 * @author yuboon
 * @version v1.0
 * @date 2020/04/12
 */
@Configuration
public class ShiroConfiguration {

    //将自己的验证方式加入容器
    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        myShiroRealm.setCredentialsMatcher(new CredentialsMatcher());
        return myShiroRealm;
    }

    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }


    // 定义shiro的过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        Map<String, Filter> filterMap = shiroFilterFactoryBean.getFilters();
        // 自定义Filter
        filterMap.put("authc",new LoginFilter());

        /**
         * Filter        拦截哪些请求应该可以配置，包括不拦截哪些请求也可以配置
         * Inteceptor
         */
        Map<String,String> map = new HashMap<String, String>();

        // key 路径，  value 进行的校验逻辑（authc：默认的一些校验过滤器  anon ： 不校验）
        //登出
        map.put("/logout","logout");
        //对所有用户认证
        map.put("/user/**","authc");
        map.put("/org/**","authc");
        map.put("/role/**","authc");
        map.put("/menu/**","authc");
        map.put("/log/**","authc");
        map.put("/index","authc");
        // map.put("/login.html","anon");
        //其他资源不拦截
        map.put("/**","anon");
        // 进行绑定
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);


        //登录
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        //首页
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //错误页面，认证不通过跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/error");
        return shiroFilterFactoryBean;
    }

}
